package wang.unclecat.databinding.utils;

import ohos.aafwk.ability.AbilitySlice;
import ohos.agp.components.ComponentContainer;

import java.lang.reflect.Field;
import java.util.Optional;

public class LayoutHelper {
    private static Field uiContent_Slice;
    private static Field curComponentContainer;

    static {

        try {
            uiContent_Slice = AbilitySlice.class.getDeclaredField("uiContent");
            uiContent_Slice.setAccessible(true);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        try {
            curComponentContainer = Class.forName("ohos.aafwk.ability.UIContent").getDeclaredField("curComponentContainer");
            curComponentContainer.setAccessible(true);
        } catch (NoSuchFieldException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static Optional<ComponentContainer> getUIContent(AbilitySlice abilitySlice) {
        if (uiContent_Slice != null && curComponentContainer != null) {
            try {
                Object uiContentObj = uiContent_Slice.get(abilitySlice);
                Object curComponentContainerObj = curComponentContainer.get(uiContentObj);
                return Optional.ofNullable((ComponentContainer) curComponentContainerObj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return Optional.empty();
    }

}
